package net.mysoft.framework.util;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.type.Type;

public class IDGenerator implements IdentifierGenerator, Configurable {
	private static final Log log = LogFactory.getLog(IDGenerator.class);
	private static final String TABLE = "tbSequence";
	
	private Serializable next;
	private String sql;
	private String seqName;//序列名
	private String way = "1";//方式
	private String pattern = "00000";//后缀长度
	public synchronized Serializable generate(SessionImplementor session, Object object)
			throws HibernateException {
		if (sql != null) {
			try {
				getNext(session.connection());
			} catch (Exception e) {
				throw new HibernateException(e);
			}
		}
		return next;

	}

	public void configure(Type type, Properties params, Dialect d)
			throws MappingException {
		seqName = params.getProperty("seq");
		if(params.getProperty("way")!=null)
			way = params.getProperty("Way");
		if(params.getProperty("pattern")!=null)
			pattern = params.getProperty("pattern");
		sql = "select CurrentValue,Prefix,Middle from " + TABLE
		+ " where SeqID = '" + seqName + "' and Way = " + way;
	}

	private void getNext(Connection conn) throws Exception {
		Date today = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String todayStr = sdf.format(today);
		String prefix = "";
		Long nextValue;
		String middle = null;
		try {
	
			PreparedStatement st = conn.prepareStatement(sql);
			ResultSet rs = st.executeQuery();
			if (rs.next()) {
				nextValue = rs.getLong(1) + 1;
				prefix = rs.getString(2);
				middle = rs.getString(3);
				if(middle==null||!todayStr.equals(middle)){
					nextValue=1L;
					middle = todayStr;
				}
			} else {
				nextValue = 1l;
			}
			String updateSql = "update " + TABLE + " set CurrentValue ="+ nextValue +",middle='"+middle+"'  where SeqID = '" + seqName + "' and Way = " + way;
			PreparedStatement st2 = conn.prepareStatement(updateSql);
			int temp = st2.executeUpdate();
			if (temp < 0) {
				throw new Exception();
			}
			java.text.DecimalFormat df = new java.text.DecimalFormat(pattern);
			next = prefix +middle+df.format(nextValue);
			conn.commit();
		} catch (SQLException e) {
			//System.out.println("ID生成错误&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
			try {
				conn.rollback();
			} catch (SQLException e1) {
				throw new HibernateException(e);
			}
			
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				throw new HibernateException(e);
			}
		}

	}
	
	/**
	 * 获取uuid
	 * @return
	 */
	public static String getId() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
}
